<?php
/*
 * create by phpstorm
 * author：Ming
 * date：2018.05.23
 * ps：内容格式化组件
 * */

namespace App\Controller\Component;
use Cake\Controller\Component;


class ContentFormatComponent extends Component
{
    public $components = ['G','Upcos'];
    public function initialize(array $config)
    {
        parent::initialize($config);
    }

    /*
     * create by phpstorm
     * author：Ming
     * date：2018.05.23
     * ps：清洗掉内容中的图片域名
     * */
    public function clean($content = null){
        $image = '';
        if(!empty($content['ops'])){
            $i = 0;
            foreach ($content['ops'] as $k=>$v){
                if(isset($v['insert']['image'])){
                    if(is_numeric(strpos($v['insert']['image'],'data:image/'))){
                        $result = $this->Upcos->upload($v['insert']['image'],['upType'=>'base64']);
                        if($i==0){
                            $image = $result['data']['fullName'];
                            $i++;
                        }
                        $content['ops'][$k]['insert']['image'] = $result['data']['fullName'];
                    }else{
                        $content['ops'][$k]['insert']['image'] = $this->G->setImgUrl($v['insert']['image']);
                        if($i==0){
                            $image = $this->G->setImgUrl($v['insert']['image']);
                            $i++;
                        }
                    }
                }
            }
        }
        return [json_encode($content),$image];
    }

    /*
     * create by phpstorm
     * author：Ming
     * date：2018.05.23
     * ps：添加指定图片域名
     * */
    public function add($content = null){
        $content = json_decode($content);
        if(!empty($content->ops)){
            foreach ($content->ops as $k=>$v){
                if(isset($v->insert->image)){
                    $content->ops[$k]->insert->image = $this->G->getImgUrl($v->insert->image, 1);
                }
            }
        }
        return $content;
    }

}